package com.hailiao.beidou.message.data.db.dao

import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.hailiao.beidou.message.data.db.entity.MatchedMessageCount
import com.hailiao.beidou.message.data.db.entity.MessageEntity

@Dao
interface MessageDao {

    // 分页数据
    @Query("SELECT * FROM message_table WHERE number = :number ORDER BY `createTime` DESC")
    fun pagingSource(number: String): PagingSource<Int, MessageEntity>

    // 查询
    @Query("SELECT * FROM message_table WHERE number = :number ORDER BY `createTime` DESC")
    fun query(number: String): PagingSource<Int, MessageEntity>

    // 模糊查询
    @Query("SELECT * FROM message_table WHERE number = :number AND content LIKE '%'||:key||'%' ORDER BY `createTime` DESC")
    suspend fun susQuery(number: String, key: String): List<MessageEntity>

    // 查询指定聊天消息在特定用户的特定对话中在第几句
    @Query("SELECT COUNT(id) FROM message_table WHERE number = :number AND createTime > :time")
    suspend fun susQueryPosition(number: String, time: Long): Long

    // 模糊查询匹配的消息数量
    @Query(
        """
    SELECT message_table.number as number, IFNULL(contact_table.name, message_table.number) as name, COUNT(*) as count
    FROM message_table
    LEFT JOIN contact_table ON message_table.number = contact_table.number
    WHERE message_table.content LIKE '%' || :key || '%'
    GROUP BY message_table.number
"""
    )
    suspend fun susQueryCount(
        key: String
    ): List<MatchedMessageCount>

    // 插入
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(info: MessageEntity): Long

    // 修改
    @Update(onConflict = OnConflictStrategy.REPLACE)
    suspend fun update(info: MessageEntity)

    // 删除
    @Delete
    suspend fun delete(info: MessageEntity)

    // 删除
    @Query("DELETE FROM message_table WHERE number = :number")
    suspend fun delete(number: String)
}